﻿using UnityEngine;

namespace Core
{
    /// <summary>
    /// 前缀 go_XXX
    /// </summary>
    public class UIWidget : Component, IGameObject, IActive, IAwake<GameObject>
    {
        public GameObject gameObject { get; private set; }
        public Transform transform { get; private set; }

        public bool Active { get; private set; }

        public virtual void Awake(GameObject go)
        {
            gameObject = go;
            transform = go.transform;

            G.UI.ParseUIField(this, go);
        }

        public virtual void Init()
        {
            if (gameObject.activeSelf)
            {
                Active = true;
                OnShow();
            }
            else
            {
                Active = false;
            }
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            SetActive(false);

            G.UI.DisposeUIField(this);

            G.Res.Recycle(gameObject);
            gameObject = null;
            transform = null;

            base.Dispose();
        }

        public virtual void SetActive(bool active)
        {
            if (Active == active)
            {
                return;
            }
            Active = active;
            Utils.Trans.SetActive(gameObject, active);
            if (active)
            {
                OnShow();
            }
            else
            {
                OnHide();
            }
        }

        protected virtual void OnShow() { }
        protected virtual void OnHide() { }

        public void SetLocalPosition(Vector3 pos)
        {
            transform.localPosition = pos;
        }

        public Vector3 GetLocalPosition()
        {
            return transform.localPosition;
        }
    }
}
